import os




from code.data.User import User
from code.data.File import File
from code.dao.file_management import add_file,delete_file,search_file
from code.dao.user_management import search_user

class FileBackend:

    @staticmethod
    def file_init_display(userin:User):
        ret = 0
        if userin.userID is None:
            ret = 2001
        else:
            file_list = search_file(File(),"all")
            if file_list is None:
                ret = 2002
            else:
                ret = file_list
        return ret

    @staticmethod
    def file_upload(userin:User,file:File):
        ret = 0
        if userin.userID is None:
            ret = 2001
        else:
            user = search_user(userin,"userID")[0]
            if user.userID != file.userID:
                ret = 2009
            elif file.userID is None:
                ret = 2011
            elif file.filename is None:
                ret = 2007
            elif file.path is None:
                ret = 2010
            elif file.size > 1000000000:
                ret = 2008
            elif search_file(file, "path") is not None:
                ret = 2014
            else:
                if add_file(file) is True:
                    ret = 1
                else :
                    ret = 0
        return ret

    @staticmethod
    def file_delete(userin:User,file: File):
        ret = 0

        if userin.userID is None:
            ret = 2001
        else:
            user = search_user(userin,"userID")[0]
            if file.userID is None:
                ret = 2012
            else:
                file_back = search_file(file, "fileID")
                if len(file_back) > 1 :
                    ret = 2005
                elif len(file_back) == 0:
                    ret = 2004
                elif file_back[0].userID != user.userID:
                    ret = 2003
                else:
                    if delete_file(file) is True:
                        ret = 1
                    else:
                        ret = 0
        return ret

    @staticmethod
    def file_download(userin:User,file:File):
        ret = 0
        if userin.userID is None:
            ret = 2001
        else:
            user = search_user(userin, "userID")[0]
            if file.userID is None:
                ret = 2013
            else:
                file_back = search_file(file, "fileID")
                if file_back is None:
                    ret = 2004
                elif len(file_back) > 1:
                    ret = 2005
                else:
                    ret = file_back[0]
        return ret






